import React, {Component} from 'react';
import {
    View,
    StyleSheet,
    ScrollView,
    TouchableOpacity,
    Text,
    FlatList,
    ActivityIndicator,
    Animated
} from 'react-native';

import RNFixedHeaderListView from '../../component/FixedHeaderListView';
import DataRepository from '../util/DataRepository';

import GlobalStyles from '../../res/styles/GlobalStyles';

import TalentItem from '../../component/TalentItem';
import EmptyDataView from '../../component/EmptyDataView';

const AnimatedFlatList = Animated.createAnimatedComponent(FlatList);

export default class TalentScreen extends Component {

    constructor(props) {
        super(props);
        this.state = {
            talentServiceArray: [],
            loading: false,
            filterArray: [],
            filterNumArray: [],
            refreshing: true,
            page: 1,
            hasNextPage: true,
            sortType: ''
        }
    }

    componentDidMount() {
        this.getFilter();
    }

    getFilter = () => {
        DataRepository
            .fetchRequest('tech/type/list')
            .then(res => {
                if (res.code == 200) {
                    let filterArray = [];
                    let filterNumArray = [];
                    filterArray.push('全部');
                    filterNumArray.push(0);
                    res
                        .data
                        .forEach(function (value) {
                            filterArray.push(value.techTypeName);
                            filterNumArray.push(value.techTypeId);
                        })
                    filterArray.push('其他');
                    filterNumArray.push(-1);
                    this.setState({filterArray: filterArray, filterNumArray: filterNumArray})
                    this.getServiceList();

                } else if (res.code == 401) {
                    storage.remove({key: 'token'});
                    this
                        .props
                        .navigation
                        .navigate('Login');
                }
            })
            .catch(err => {
                this.setState({refreshing: false});
            })
    }

    getServiceList = () => {
        DataRepository
            .fetchRequest('talent/service/list?page=' + this.state.page + '&sort=' + this.state.sortType)
            .then(res => {
                if (res.code == 200) {
                    if (res.data.pageNum == 1 || res.data.pageNum == 0) {
                        var serviceArray = [];
                        serviceArray.push({key: -1, value: res.data.list[0]})
                        res
                            .data
                            .list
                            .forEach(function (item, index) {
                                serviceArray.push({key: index, value: item});
                            })

                        this.setState({talentServiceArray: serviceArray, hasNextPage: res.data.hasNextPage});

                    } else if (res.data.total == 0) {
                        this.setState({talentServiceArray: [], hasNextPage: res.data.hasNextPage});
                        this.renderEmptyView();
                    } else {
                        var serviceArray = [];
                        var length = this.state.talentServiceArray.length;
                        res
                            .data
                            .list
                            .forEach(function (item, index) {
                                serviceArray.push({
                                    key: length + index - 1,
                                    value: item
                                });
                            });
                        this.setState({
                            talentServiceArray: this
                                .state
                                .talentServiceArray
                                .concat(serviceArray)
                        }, () => {
                            this.setState({hasNextPage: res.data.hasNextPage});
                        });
                    }

                } else if (res.code == 401) {
                    storage.remove({key: 'token'});
                    this
                        .props
                        .navigation
                        .navigate('Login');

                }
                this.setState({refreshing: false, loading: false});
            })
            .catch(err => {
                this.setState({refreshing: false, loading: false});
            })

    }

    /**加载更多 */
    handleLoadMore = () => {
        if (this.state.loading) {
            return;
        }
        if (this.state.hasNextPage) {
            this.setState({
                loading: true,
                page: this.state.page + 1
            }, () => {
                this.getServiceList();
            });
        }

    }

    /**下拉刷新 */
    handleRefresh = () => {
        if (this.state.loading) {
            return;
        }
        this.setState({
            loading: true,
            page: 1,
            hasNextPage: true
        }, () => {
            this.getServiceList();
        });
    };
    /**渲染底部 */
    renderFooter = () => {
        if (this.state.hasNextPage) {
            return (
                <ActivityIndicator></ActivityIndicator>
            );
        } else {
            return (
                <View
                    alignItems='center'
                    style={{
                    margin: 4
                }}>
                    <Text style={{
                        color: 'grey'
                    }}>已经到底了！</Text>
                </View>
            );
        }

    };
    /**渲染条目 */
    renderItem = ({item, index}) => {
        return (
            <TalentItem
                talentServiceArray={this.state.talentServiceArray[index].value}
                filterArray={this.state.filterArray}
                filterNumArray={this.state.filterNumArray}
                filterPress={this.filterPress}
                index={index}></TalentItem>
        );
    };
    /**点击过滤 */
    filterPress = (sortType) => {
        if (this.state.loading) {
            return;
        }
        this.setState({
            sortType: sortType,
            refreshing: true,
            page: 1,
            loading: true
        }, () => {
            this.getServiceList();
        });
    };

    renderEmptyView = () => {
        return (
            <EmptyDataView></EmptyDataView>
        );
    };

    render() {
        var filter = [];
        for (let i = 0; i < this.state.filterArray.length; i++) {
            filter.push(
                <TouchableOpacity
                    key={i}
                    onPress={() => {
                    this.onPress(this.state.filterNumArray[i])
                }}>
                    <View style={GlobalStyles.circle}>
                        <Text
                            style={{
                            color: 'white'
                        }}>{this.state.filterArray[i]}</Text>
                    </View>
                </TouchableOpacity>
            );
        }

        return (
            <View style={styles.filterBar}>
                <FlatList
                    style={styles.flatlist}
                    refreshing={this.state.refreshing}
                    onRefresh={this.handleRefresh}
                    ListFooterComponent={this.renderFooter}
                    data={this.state.talentServiceArray}
                    stickyHeaderIndices={[0]}
                    renderItem={this.renderItem}
                    onEndReached={this.handleLoadMore}
                    onEndReachedThreshold={0.1}/>
            </View>
        );

    }
}

// 设置样式
const styles = StyleSheet.create({
    filterBar: {
        justifyContent: 'center'
    },
    flatlist: {
        height: '100%',
        width: '100%'
    }
});
